/**
 * 
 */
package org.crown.kings.jsf.formatters.en_US;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.crown.kings.jsf.PhoneNumberBean;
import org.crown.kings.jsf.formatters.BeanFormatException;
import org.crown.kings.jsf.formatters.BeanFormatter;

/**
 * @author nagood
 * 
 */
public class PhoneNumberBeanFormatterImpl implements BeanFormatter
{

	public enum PhoneNumberFormat
	{

		BASIC("(nnn) nnn-nnnn"), DASHES("nnn-nnn-nnnn"), DOTS("nnn.nnn.nnnn");

		public static PhoneNumberFormat parseFormat(final String format)
		{
			if (format == null) {
				throw new IllegalArgumentException("Argument cannot be null.");
			}

			for (final PhoneNumberFormat fmt : PhoneNumberFormat.values()) {
				if (format.equals(fmt.getFormatString())) {
					return fmt;
				}
			}
			throw new IllegalArgumentException("Invalid format \"" + format + "\"");
		}

		private final String formatString;

		private PhoneNumberFormat(final String format)
		{
			formatString = format;
		}

		/**
		 * @return the formatString
		 */
		public String getFormatString()
		{
			return formatString;
		}

	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -1796961334452439091L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.crown.kings.jsf.formatters.BeanFormatter#format(java.lang.Object)
	 */
	public String format(final Object o)
	{
		if (o instanceof PhoneNumberBean) {
			final PhoneNumberBean phoneNumber = (PhoneNumberBean) o;
			return PhoneNumberBeanFormatterImpl.formatNumber(PhoneNumberFormat.BASIC, phoneNumber.getPhoneNumber());
		} else {
			return StringUtils.EMPTY;
		}
	}

	/**
	 * 
	 * @param format
	 * @param value
	 * @return
	 */
	public static String formatNumber(PhoneNumberFormat format, String value)
	{
		String result = value;

		switch (format) {
		case BASIC:
			result = applyBasicFormat(value);
			break;
		}

		return result;
	}

	/**
	 * Applies the BASIC format to the phone number.
	 * @param value
	 * @return
	 */
	private static String applyBasicFormat(String value)
	{
		String result = value;
		if (value != null) {
			Pattern re = Pattern.compile("^\\(?(\\d{3})\\)?[-.\\s]?(\\d{3})[-.\\s]?(\\d{4})$");

			Matcher matches = re.matcher(value);
			if (matches.matches()) {
				result = "(" + matches.group(1) + ") " + matches.group(2) + "-" + matches.group(3);
			}
		}

		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.crown.kings.jsf.formatters.BeanFormatter#parse(java.lang.String)
	 */
	public Object parse(final String s) throws BeanFormatException
	{
		// TODO Auto-generated method stub
		return null;
	}

}
